<template>
    <div>
        <el-card class="!border-none mb-4" shadow="never">
            <div class="flex flex-wrap">
                <div class="w-1 md:w-1/2">
                    <div class="leading-10">点券余额</div>
                    <div class="text-6xl">{{ Number(userInfo?.total_cost_amount || 0).toFixed(2) }}</div>
                </div>
                <div class="w-1 md:w-1/2">
                    <div class="leading-10">累计充值金额 (元)</div>
                    <div class="text-6xl">{{ Number(userInfo?.total_recharge_amount || 0).toFixed(2) }}</div>
                </div>
            </div>
        </el-card>
        <el-card class="!border-none" shadow="never">
            <el-form ref="formRef" class="mb-[-16px] mt-[16px]" :model="queryParams" :inline="true">
                <el-form-item class="w-[280px]" label="变动类型">
                    <el-select v-model="queryParams.transaction_type">
                        <el-option label="全部" value />
                        <el-option
                            v-for="(value, key) in optionsData.transaction_type"
                            :key="key"
                            :label="value"
                            :value="key"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="记录时间">
                    <daterange-picker
                        v-model:startTime="queryParams.start_time"
                        v-model:endTime="queryParams.end_time"
                    />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="resetPage">查询</el-button>
                    <el-button @click="resetParams">重置</el-button>
                    <el-button type="danger" @click="sendCoupon">赠送</el-button>
                </el-form-item>
            </el-form>
        </el-card>
        <el-card class="!border-none mt-4" shadow="never">
            <el-table size="large" v-loading="pager.loading" :data="pager.lists">
                <el-table-column label="变动点券" prop="change_amount" min-width="100">
                    <template #default="{ row }">
                        <span :class="{ 'text-error': row.action == 2 }">{{ row.change_amount }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="剩余点券" prop="left_amount" min-width="100" />
                <el-table-column label="变动类型" prop="transaction_type_desc" min-width="120" />
                <el-table-column label="来源单号" prop="source_id" min-width="100" />
                <el-table-column label="记录时间" prop="create_time" min-width="120" />
            </el-table>
            <div class="flex justify-end mt-4">
                <pagination v-model="pager" @change="getLists" />
            </div>
        </el-card>
    </div>
    <!-- 赠送弹窗 -->
    <el-dialog v-model="dialogVisible" title="赠送点券" width="550px">
        <div class="space-y-4 p-4">
            <div>
                <div class="text-gray-600 mb-2">赠送账号</div>
                <el-input
                    v-model="giftAccount"
                    type="text"
                    placeholder="请输入赠送账号"
                    clearable
                    :loading="accountLoading"
                    @input="handleGiftAccountInput"
                    @clear="handleGiftAccountClear"
                />
            </div>
            
            <!-- 账号信息显示区域 -->
            <div v-if="targetUserInfo" class="p-3 border rounded-lg bg-gray-50">
                <div class="flex items-center space-x-3">
                    <img :src="targetUserInfo.avatar || 'default-avatar.png'" alt="头像" class="w-12 h-12 rounded-full object-cover">
                    <div>
                        <div class="font-medium">{{ targetUserInfo.name }}</div>
                        <div class="text-sm text-gray-500">{{ targetUserInfo.mobile }}</div>
                    </div>
                </div>
            </div>
            
            <div>
                <div class="text-gray-600 mb-2">当前余额</div>
                <div class="text-xl font-bold">{{ Number(userInfo?.total_cost_amount || 0).toFixed(2) }}</div>
            </div>
            <div>
                <div class="text-gray-600 mb-2">赠送点券</div>
                <el-input
                    v-model="giftAmount"
                    type="text"
                    placeholder="请输入赠送金额"
                    :max="Number(userInfo?.total_cost_amount || 0)"
                    clearable
                    @input="handleGiftAmountInput"
                    @clear="handleGiftAmountClear"
                />
                <div v-if="Number(giftAmount || 0) > Number(userInfo?.total_cost_amount || 0)" class="text-red-500 text-sm mt-1">
                    赠送金额不能超过当前余额
                </div>
            </div>
            <div>
                <div class="text-gray-600 mb-2">赠送后余额</div>
                <div class="text-xl font-bold">{{ newBalance.toFixed(2) }}</div>
            </div>
            <div>
                <div class="text-gray-600 mb-2">备注</div>
                <el-input
                    v-model="remark"
                    type="textarea"
                    placeholder="请输入备注信息"
                />
            </div>
        </div>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="confirmSend">确定</el-button>
            </span>
        </template>
    </el-dialog>
</template>
<script lang="ts" setup name="balanceDetail">
import { accountLog, getUmChangeType } from '@/api/finance'
import { useDictOptions } from '@/hooks/useDictOptions'
import { usePaging } from '@/hooks/usePaging'
import { getUserInfo, getUserInfoByAccount, giftPoint } from '@/api/user'
import { ref, onMounted, reactive, watch } from 'vue'
import { ElMessage } from 'element-plus'

// 定义用户信息响应式变量
const userInfo = ref<{ total_recharge_amount: string; total_cost_amount: string; account: string } | null>(null)
// 赠送弹窗相关变量
const dialogVisible = ref(false)
const giftAccount = ref('') // 赠送账号
const giftAmount = ref('0') // 赠送金额
const remark = ref('') // 备注
const newBalance = ref(0) // 赠送后余额
const targetUserInfo = ref<{ avatar: string; name: string; mobile: string } | null>(null) // 目标账号信息
const accountLoading = ref(false) // 账号查询加载状态

const queryParams = reactive({
    transaction_type: '',
    start_time: '',
    end_time: ''
})

const { pager, getLists, resetPage, resetParams } = usePaging({
    fetchFun: accountLog,
    params: queryParams
})

const { optionsData } = useDictOptions<{
    transaction_type: Record<number, string>
}>({
    transaction_type: {
        api: getUmChangeType
    }
})

// 计算赠送后余额
const calculateNewBalance = () => {
    const currentBalance = Number(userInfo.value?.total_cost_amount || 0)
    const giftValue = giftAmount.value ? Number(giftAmount.value) : 0
    
    // 限制赠送金额不能超过当前余额
    if (giftValue > currentBalance) {
        giftAmount.value = currentBalance.toFixed(2)
    } else if (giftValue < 0) {
        giftAmount.value = '0'
    }
    
    newBalance.value = Number((currentBalance - (giftAmount.value ? Number(giftAmount.value) : 0)).toFixed(2))
}

// 处理赠送金额清空
const handleGiftAmountClear = () => {
    giftAmount.value = ''
    calculateNewBalance()
}

// 处理赠送金额输入
const handleGiftAmountInput = () => {
    // 允许空值
    if (!giftAmount.value) {
        giftAmount.value = ''
        calculateNewBalance()
        return
    }
    
    // 过滤非数字和非小数点字符
    giftAmount.value = giftAmount.value.replace(/[^0-9.]/g, '')
    
    // 确保只有一个小数点
    const parts = giftAmount.value.split('.')
    if (parts.length > 2) {
        giftAmount.value = parts[0] + '.' + parts[1]
    }
    
    // 限制小数点后最多2位
    if (parts.length === 2 && parts[1].length > 2) {
        giftAmount.value = parts[0] + '.' + parts[1].substring(0, 2)
    }
    
    // 处理首位为0的情况
    // 如果输入以0开头，且长度大于1，且第二个字符不是小数点，则只保留第一个0
    if (giftAmount.value.startsWith('0') && giftAmount.value.length > 1 && giftAmount.value[1] !== '.') {
        giftAmount.value = '0' + (parts.length === 2 ? '.' + parts[1] : '')
    }
    
    calculateNewBalance()
}

// 处理账号输入
const handleGiftAccountInput = async () => {
    if (!giftAccount.value.trim()) {
        targetUserInfo.value = null
        return
    }

    // 防抖处理，避免频繁请求
    clearTimeout(window.giftAccountTimer)
    window.giftAccountTimer = setTimeout(async () => {
        try {
            accountLoading.value = true
            // 调用接口获取账号信息
            const res = await getUserInfoByAccount({ account: giftAccount.value })
            if (res && res.account) {
                targetUserInfo.value = {
                    avatar: res.avatar || '',
                    name: res.name || '',
                    mobile: res.mobile || ''
                }
                
            } else {
                targetUserInfo.value = null
            }
        } catch (error) {
            console.error('获取账号信息失败:', error)
            ElMessage.error('获取账号信息失败')
            targetUserInfo.value = null
        } finally {
            accountLoading.value = false
        }
    }, 500)
}

// 处理账号清空
const handleGiftAccountClear = () => {
    giftAccount.value = ''
    targetUserInfo.value = null
    clearTimeout(window.giftAccountTimer)
}

// 打开赠送弹窗
const sendCoupon = () => {
    giftAccount.value = ''
    giftAmount.value = '0'
    remark.value = ''
    targetUserInfo.value = null
    calculateNewBalance()
    dialogVisible.value = true
}

// 确认赠送
const confirmSend = async () => {
    if (!giftAccount.value.trim()) {
            ElMessage.warning('请输入赠送账号')
            return
        }

        if (!targetUserInfo.value) {
            ElMessage.warning('没有获取到赠送用户信息，请检查账号是否正确')
            return
        }

        if (!giftAmount.value || isNaN(Number(giftAmount.value)) || Number(giftAmount.value) <= 0) {
            ElMessage.warning('请输入有效的赠送金额')
            return
        }

        // 检查是否是给自己赠送
        if (giftAccount.value === userInfo.value?.account) {
            ElMessage.warning('不能给自己赠送点券')
            return
        }

        const giftValue = Number(giftAmount.value)
        const currentBalance = Number(userInfo.value?.total_cost_amount || 0)

        if (giftValue > currentBalance) {
            ElMessage.warning('赠送金额不能超过当前余额')
            return
        }

    try {
        // 这里替换为实际的赠送API调用
         await giftPoint({
           gift_account: giftAccount.value,
           amount: giftValue,
           remark: remark.value
         })
        ElMessage.success('赠送成功')
        dialogVisible.value = false
        fetchUserInfo()
        getLists()
    } catch (error) {
        ElMessage.error('赠送失败，请重试')
        console.error('赠送失败:', error)
    }
}

// 获取用户信息函数
const fetchUserInfo = async () => {
    try {
        const res = await getUserInfo()
        if (res && res.user) {
            userInfo.value = res.user
            console.log('用户信息获取成功:', userInfo.value)
        } else {
            console.error('获取用户信息失败: 响应格式不正确')
            ElMessage.warning('获取用户信息不完整')
            
            
        }
    } catch (error) {
        console.error('获取用户信息失败:', error)
        ElMessage.error('获取用户信息失败')
    
        
    }
}

// 监听giftAmount变化，实时计算新余额
watch(giftAmount, (newValue) => {
    calculateNewBalance()
})

// 在组件挂载时获取用户信息
onMounted(() => {
    fetchUserInfo()
    getLists()
})
</script>